import { _decorator, Component, EventTouch, Input, Node, UITransform, Vec2, Vec3 } from 'cc';
import { preBlockClick } from './preBlockClick';
import { gameState } from './gameState';
import { layerRootAction } from './layerRootAction';
const { ccclass, property } = _decorator;

@ccclass('layerAction_002')
export class layerAction_002 extends Component {
    cur_block_action:preBlockClick = null; 
    start() {
        if(gameState.game_model ===1){
            return;
        }
        this.node.on(Input.EventType.TOUCH_END,this.touch_end,this)
        this.node.on(Input.EventType.TOUCH_START,this.touch_start,this)
        this.node.on(Input.EventType.TOUCH_CANCEL,this.touch_cancel,this)
    }
    touch_end(e:EventTouch){
        let pos = e.getUILocation();//getLocation

        if(this.cur_block_action){
            this.cur_block_action.play_end_tween();
        }else{
            return;
        }
        let block_action = this.get_touch_block(pos);
        if(this.cur_block_action!=block_action){
            return;
        }
        this.cur_block_action.set_temp_pos(this.cur_block_action.node.getWorldPosition());
        this.node.parent.getComponent(layerRootAction).play_sound(0);
        this.node.parent.getComponent(layerRootAction).to_3_from_2(this.cur_block_action);
    }   
    touch_start(e:EventTouch){
        let pos = e.getUILocation();//getLocation
        console.info(pos);
        let block_action = this.get_touch_block(pos);
        this.cur_block_action = block_action;
        if(this.cur_block_action){
            this.cur_block_action.play_start_tween();
        }
        
    }
    touch_cancel(e:EventTouch){
        if(this.cur_block_action){
            this.cur_block_action.play_end_tween();
        }
    }
    get_touch_block(pos_world:Vec2):preBlockClick{
        let local = this.node.getComponent(UITransform).convertToNodeSpaceAR(new Vec3(pos_world.x,pos_world.y));
        console.info(local);
        for (let i = this.node.children.length - 1; i >= 0; i--) {
            let ele = this.node.children[i];
            if (!ele.active) {
                continue;
            }
            let block_action = ele.getComponent(preBlockClick);
            if(!block_action.can_touch()){
                continue;
            }
            if(block_action.get_bounding_box().contains(new Vec2(local.x,local.y))){
                return block_action;
            }
        }
        return null;
    }
    get_block_size():number{
        return this.node.children.length;
    }
    get_zero_world_position():Vec3{
        return this.node.getComponent(UITransform).convertToWorldSpaceAR(new Vec3(0,0,0))

    }
    add_block(block_action:preBlockClick){
        block_action.node.setPosition(0,0);
        block_action.node.setParent(this.node);
    }
    clear_all(){
        this.node.removeAllChildren();
    }
    update(deltaTime: number) {
        
    }
}


